using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BagScroll : MonoBehaviour
{
    [SerializeField] private BagContent bagContent;

    [SerializeField, Range(0.1f, 10f)]
    private float scrollSensitivity = 1f; // 滚轮灵敏度

    [SerializeField] private float moveDuration = 0.3f; // 滑动动画时长

    private float scrollAccumulator = 0f;
    private float scrollThreshold = 1f; // 移动一次的滚轮阈值

    private bool isMoving = false;
    private float currentOffset = 0f; // 当前总偏移量

    void Update()
    {
        if (bagContent == null || bagContent.ContentParent == null) return;

        float scrollDelta = Input.mouseScrollDelta.y * scrollSensitivity;
        if (scrollDelta == 0) return;

        scrollAccumulator += scrollDelta;

        while (scrollAccumulator >= scrollThreshold)
        {
            MoveContent(-1); // 滚轮向上 → 内容向下
            scrollAccumulator -= scrollThreshold;
        }
        while (scrollAccumulator <= -scrollThreshold)
        {
            MoveContent(1); // 滚轮向下 → 内容向上
            scrollAccumulator += scrollThreshold;
        }
    }

    private void MoveContent(int direction) // 1 上，-1 下
    {
        if (isMoving) return;

        float step = bagContent.StepY; // 无论布局方向，都使用 StepY
        float newOffset = currentOffset + step * direction;

        float maxOffset = GetMaxOffset();
        float minOffset = 0f;

        if (newOffset < minOffset || newOffset > maxOffset) return;

        Vector3 moveVec = Vector3.up * step * direction; // 永远垂直偏移
        StartCoroutine(MoveCoroutine(moveVec));
        currentOffset = newOffset;
    }

    private float GetMaxOffset()
    {
        int totalRows = bagContent.GetTotalRows();
        float containerHeight = GetContainerHeight();
        float visibleRows = Mathf.Floor(containerHeight / bagContent.StepY);
        return Mathf.Max(0, (totalRows - visibleRows) * bagContent.StepY);
    }

    private float GetContainerHeight()
    {
        if (bagContent.ContentParent == null) return 10f;
        RectTransform rt = bagContent.ContentParent as RectTransform;
        if (rt != null) return rt.rect.height;

        Renderer rend = bagContent.ContentParent.GetComponent<Renderer>();
        return rend != null ? rend.bounds.size.y : 10f;
    }

    private IEnumerator MoveCoroutine(Vector3 offset)
    {
        isMoving = true;
        float elapsed = 0f;

        List<Vector3> startPositions = new List<Vector3>();
        List<Vector3> endPositions = new List<Vector3>();

        foreach (var view in bagContent.GetViews())
        {
            if (view is MonoBehaviour mono)
            {
                startPositions.Add(mono.transform.localPosition);
                endPositions.Add(mono.transform.localPosition + offset);
            }
        }

        while (elapsed < moveDuration)
        {
            elapsed += Time.deltaTime;
            float t = Mathf.Clamp01(elapsed / moveDuration);
            for (int i = 0; i < startPositions.Count; i++)
            {
                var mono = bagContent.GetViews()[i] as MonoBehaviour;
                if (mono != null)
                    mono.transform.localPosition = Vector3.Lerp(startPositions[i], endPositions[i], t);
            }
            yield return null;
        }

        for (int i = 0; i < endPositions.Count; i++)
        {
            var mono = bagContent.GetViews()[i] as MonoBehaviour;
            if (mono != null)
                mono.transform.localPosition = endPositions[i];
        }

        isMoving = false;
    }
}
